#Grab LAPOP Data 
#Convert to R Datafile

#####Clear Data and Packages####

rm(list = ls())


library(readr)
library(tidyverse)
library(readstata13)
library(foreign)
library(haven)
library(countrycode)
library(reshape2)
library(readxl)
library(wbstats)
library(here)


#####Load in LAPOP Data####

lapop.full <- read_dta("./data/2004-2018 LAPOP AmericasBarometer Merge (v1.0w).dta")
lapop.full <- as_tibble(lapop.full)

#Lapop from 2010 - 2018/19 
lapop.full$wave <- as.numeric(lapop.full$wave)
lapop.slim <- filter(lapop.full, wave > 2008)

#Country names
lapop.slim <- lapop.slim %>%
  mutate(country = as_factor(pais), 
         pais = as.numeric(pais), 
         wave = as.numeric(wave), 
         year = as.numeric(year))

#Keep 18 Latin American Countries
lapop.slim <- filter(lapop.slim, pais < 22)


#ISO3c Code
lapop.slim$iso3c <- countrycode(lapop.slim$country, 
                                origin = "country.name",
                                destination = "iso3c")


save(lapop.slim, file = here("./data/lapop_slim.RData"))


